package com.atguigu.yygh.common.handler;

import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;

// 由@ControllerAdvice 标记的类都表示全局异常处理类
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /*
    *    输出异常到日志文件
    *    @ResponseBody  解析Json格式的数据
    * */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public R handleException(Exception ex){
        ex.printStackTrace();
        log.error(ex.getMessage());
        return R.error().Message(ex.getMessage());
    }

//    会优先走细粒度的异常
    @ResponseBody
    @ExceptionHandler(value = SQLException.class)
    public R handleSqlException(Exception ex){
        ex.printStackTrace();
        log.error(ex.getMessage());
        return R.error().Message("Sql异常");
    }

    @ResponseBody
    @ExceptionHandler(value = ArithmeticException.class)
    public R handleArithmeticException(Exception ex){
        ex.printStackTrace();
        return R.error().Message("数学异常");
    }

    @ResponseBody
    @ExceptionHandler(value = RuntimeException.class)
    public R handleRuntimeException(Exception ex){
        ex.printStackTrace();
        log.error(ex.getMessage());
        return R.error().Message("运行时异常");
    }

    @ResponseBody
    @ExceptionHandler(value = NullPointerException.class)
    public R handleNullPointerException(Exception ex){
        ex.printStackTrace();
        log.error(ex.getMessage());
        return R.error().Message("空指针异常");
    }

    @ResponseBody
    @ExceptionHandler(value = YyghException.class)
    public R handleYyghException(YyghException ex){
        ex.printStackTrace();
        log.error(ex.getMessage());
        return R.error().Message(ex.getMessage()).Code(ex.getCode());
    }

}
